package com.ueboot.weishop.api.controller.setting;

import com.ueboot.core.http.response.Response;
import com.ueboot.weishop.api.controller.setting.vo.CategoryReq;
import com.ueboot.weishop.api.controller.setting.vo.CategoryResp;
import com.ueboot.weishop.entity.setting.*;
import com.ueboot.weishop.service.setting.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品分类管理
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/public/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    @RequestMapping(value = "/find",method = RequestMethod.POST)
    public Response<List<CategoryResp>> find() {
        List<CategoryEntity> result = categoryService.findAll();
        List<CategoryResp> list = new ArrayList<>();
        result.forEach(item -> {
            CategoryResp resp = new CategoryResp();
            BeanUtils.copyProperties(item, resp);
            if (item.getParent() != null) {
                resp.setParentId(item.getParent().getId());
            }
            resp.setValue(item.getId());
            list.add(resp);
        });
        return new Response<>(list);
    }


    @RequiresPermissions("category:save")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Response<Void> save(@RequestBody CategoryReq req) {
        CategoryEntity entity = null;
        if (req.getId() == null) {
            entity = new CategoryEntity();
        } else {
            entity = categoryService.get(req.getId());
        }
        BeanUtils.copyProperties(req, entity);

        if (req.getParentId() != null) {
            CategoryEntity parent = categoryService.get(req.getParentId());
            entity.setParent(parent);

            entity.setFullPathName(parent == null || parent.getFullPathName() == null ?  null : parent.getFullPathName() + parent.getName() + "/");
            entity.setFullPathId(parent == null || parent.getFullPathId() == null ? null : parent.getFullPathId() + parent.getId() + "/");

        }

        categoryService.save(entity);

        return new Response<>();
    }

    @RequiresPermissions("category:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Response<Void> delete(Long[] ids) {
        categoryService.delete(ids);
        return new Response<>();
    }

    @RequiresPermissions("category:read")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Response<CategoryResp> get(@PathVariable Long id) {
        CategoryEntity entity = categoryService.get(id);
        CategoryResp resp = new CategoryResp();
        BeanUtils.copyProperties(entity, resp);
        return new Response<>(resp);
    }

}
